import $C from '@/common/config'
import http from '../axios.js'
let time = Date.parse(new Date()) / 1000
class appToken {
	constructor() { 
		this.verifyUrl = $C.api_url + 'sapi/auth/verifyToken';
		this.mergeModeUrl = $C.api_url + 'sapi/auth/mergeMode'; 
	}

	//初始化登陆
	verify() { 
		console.log("app验证token") 
		var token = uni.getStorageSync('token'); //获取缓存2
		console.log("app验证token值：",token) 
		if (!token) { 
			this.getTokenFromServer();
		} else {
			this._veirfyFromServer(token); //验证token是否过期，过期调用.getTokenFromServer函数获取
		} 
	}
	
	//验证token
	_veirfyFromServer(token) {
		var that = this;
		uni.request({
			url: that.verifyUrl,
			method: 'POST',
			data: {
				token: token
			},
			success: function(res) {
				var valid = res.data.data.isValid;
				console.log("app valid值：",valid) 
				if (!valid) {
					that.getTokenFromServer();
				}
			}
		})
	}
	getTokenFromServer() {
		var that = this;
		uni.login({
		  provider: 'weixin',
		  success: function (loginRes) { 
		    // 获取用户信息
		    uni.getUserInfo({
		      provider: 'weixin', 
			  success: data => {
				console.log(data.userInfo); 
			  	if(data.errMsg=="getUserInfo:ok"){
					let post_data = data.userInfo
					post_data.loginType = 'auto'
					that.wxLogin(post_data)
				}
			  }
		    });
		  }
		});
	}
	wxLogin(data) {
		const that = this 
		uni.request({
			url: $C.api_url + 'sapi/auth/appLogin',
			method: 'POST',
			data: data, 
			success: function(res) { 
				uni.setStorageSync('token', res.data.data.token);
				let arr={}
				arr['data'] = res.data.data.my
				arr['save_time']=time
				uni.setStorageSync('my', arr);
			},
		});
	}
	 
	
	
}
export {
	appToken
};


